/**
 * Project Name:kany-utils
 * File Name:AopTargetUtils.java
 * Package Name:me.kany.utils.springutils
 * Date:2016年9月20日下午10:19:32
 * Copyright (c) 2016, Jason.Wang All Rights Reserved.
 */
package me.kany.utils.springutils;

import java.lang.reflect.Field;

import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;

/**
 * ClassName:AopTargetUtils<br/>
 * Function: 能获取JDK动态代理/CGLIB代理对象代理的目标对象<br/>
 * Date:2016年9月14日上午11:19:19<br/>
 * 
 * @author Jason.Wang
 * @version 1.0
 * @since JDK1.7
 * @see
 */
public class AopTargetUtils {
	/**
	 * 获取 目标对象
	 * 
	 * @param proxy 代理对象
	 * @return
	 * @throws Exception
	 */
	public static Object getTarget(Object proxy) throws Exception {
		if (!AopUtils.isAopProxy(proxy)) {
			return proxy;// 不是代理对象
		}
		if (AopUtils.isJdkDynamicProxy(proxy)) {
			return getJdkDynamicProxyTargetObject(proxy);
		} else { // cglib
			return getCglibProxyTargetObject(proxy);
		}
	}

	/**
	 * 
	 * getCglibProxyTargetObject: CGLIB代理对象代理的目标对象. <br/>
	 *
	 * @author Jason.Wang
	 * @version 1.0
	 * @param proxy
	 * @return
	 * @throws Exception
	 * @since JDK1.7
	 *
	 */
	private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
		Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
		h.setAccessible(true);
		Object dynamicAdvisedInterceptor = h.get(proxy);
		Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
		advised.setAccessible(true);
		Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
		return target;
	}

	/**
	 * 
	 * getJdkDynamicProxyTargetObject: 获取JDK动态代理的目标对象. <br/>
	 *
	 * @author Jason.Wang
	 * @version 1.0
	 * @param proxy
	 * @return
	 * @throws Exception
	 * @since JDK1.7
	 *
	 */
	private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
		Field field = proxy.getClass().getSuperclass().getDeclaredField("h");
		field.setAccessible(true);
		AopProxy aopProxy = (AopProxy) field.get(proxy);
		Field advised = aopProxy.getClass().getDeclaredField("advised");
		advised.setAccessible(true);
		Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
		return target;
	}
}
